import { login, logout,getInfo } from '@/api/index'
import { getToken, setToken, removeToken} from '@/utils/auth'
// import router, { resetRouter } from '@/router'
import Cookies from 'js-cookie'
import { getUserInfo } from "@/api/userinfo.js"

const state = {
  token: getToken(),
  userInfomsg: {},
  roles: [],
  activeSuject:{},
}

const mutations = {
  checkActiveSuject(state,data){
    state.activeSuject = data;
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NICKNAME: (state, userInfomsg) => {
    state.userInfomsg = userInfomsg
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const data = response.result
        console.log(data)
        if(response.code==200){
          commit('SET_TOKEN', data.token)
          Cookies.set('admin_id', data.signUsers.id)
          setToken(data.token)
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo({
          userId: Cookies.get('admin_id')
        }).then(res => {
          commit('SET_NICKNAME', res.result)
          resolve(res.result)
        }).catch(error => {
          reject(error)
        })
      })
  },





  // user logout
  logout({ commit, state, dispatch }) {
        console.log(123);

    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      removeToken()
      // resetRouter()
      Cookies.remove('admin_id')
      // dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
      // logout(state.token).then(() => {
      //   console.log(123);
        
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      //commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
//   async changeRoles({ commit, dispatch }, role) {
//     const token = role + '-token'

//     commit('SET_TOKEN', token)
//     setToken(token)

//     const { roles } = await dispatch('getInfo')

//     resetRouter()

//     // generate accessible routes map based on roles
//     const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
//     // dynamically add accessible routes
//     router.addRoutes(accessRoutes)

//     // reset visited views and cached views
//     dispatch('tagsView/delAllViews', null, { root: true })
//   }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
